package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    /**
     * 添加菜单
     * @param menu
     */
    @Override
    public void add(Menu menu) throws RuntimeException {
        //根据菜单名称查找菜单id
        try {
            Integer id = menuDao.findByName(menu.getLevelname());
            if(id!=0&&id!=null){
                menu.setParentMenuId(id);
            }
            menuDao.add(menu);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException("添加用户失败");
        }
    }

    /**
     * 分页查询菜单
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //之前：业务逻辑1.查询总记录数  2.查询当前页面显示数据
        //1.设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        //2.需要分页的语句
        Page<Menu> menuPage = menuDao.selectByCondition(queryString);
        return new PageResult(menuPage.getTotal(),menuPage.getResult());
    }

    @Override
    public List<String> findByLevel(Integer level) {
        return menuDao.findByLevel(level);
    }

    /**
     * 删除菜单
     * @param id
     */
    @Override
    public void delete(Integer id) {
        int count = menuDao.findById(id);
        if (count > 0){
            throw new RuntimeException(MessageConstant.DELETE_ROLEANDMenu_FAIL);
        }else {
            menuDao.delete(id);
        }
    }
    /*通过id查询数据回显*/
    @Override
    public Result findById(String id) {

        try {
            Menu menuById = menuDao.getMenuById(id);
            return new Result(true,"查询成功",menuById);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }

    }
    //修改会员数据
    @Override
    public void editMenu(Menu menu) throws RuntimeException {
        try {
            menuDao.editMenu(menu);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException("添加失败");
        }
    }
}
